package simpleWave;

import java.util.ArrayList;

public class Synchronizer {

	private int numThreads = 0;
	private int numCheckedIn = 0;
	private int numTimeunitsLeft = 100;

	private ArrayList<SynchronizedListener> synchronizedListener = new ArrayList<SynchronizedListener>();

	public synchronized void checkIn(long id) {
		// Increment num threads checked in
		numCheckedIn++;

		if (numCheckedIn == numThreads) {
			// All threads have checked in, go to next iteration
			numCheckedIn = 0;
			fireSynchronizedListeners();

			numTimeunitsLeft--;

			if (numTimeunitsLeft > 0) {
				notifyAll();
			}
		} else if (numCheckedIn > numThreads) {
			throw (new SynchronizerException(
					"Synchronizer has been compromised and can "
							+ "no longer guarantee synchronization!"));

		} else {
			// After checking in threads wait until all threads checked in
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void fireSynchronizedListeners() {
		for (SynchronizedListener listener : getSynchronizedListener()) {
			listener.synchronizationPerformed();
		}
	}

	public void setNumThreads(int numThreads) {
		this.numThreads = numThreads;
	}

	public void addSynchronizedListener(SynchronizedListener listener) {
		this.synchronizedListener.add(listener);
	}

	public void setSynchronizedListener(
			ArrayList<SynchronizedListener> synchronizedListener) {
		this.synchronizedListener = synchronizedListener;
	}

	public synchronized ArrayList<SynchronizedListener> getSynchronizedListener() {
		return synchronizedListener;
	}
}